package com.geezdata.cps.sdk3rd.wechat.method;

import java.io.IOException;
import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.base.utils.JaxbUtil;
import com.geezdata.cps.sdk3rd.wechat.request.WechatPayOrderQueryRequest;
import com.geezdata.cps.sdk3rd.wechat.response.WechatPayOrderQueryResult;

public class WechatPayOrderQuery extends WechatPay implements Wechat<WechatPayOrderQueryRequest, WechatPayOrderQueryResult> {
	private static final Logger logger = LoggerFactory.getLogger(WechatPayOrderQuery.class);
	
	public static String PayOrderQuery_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
	
	@Override
	public WechatPayOrderQueryResult execute(WechatPayOrderQueryRequest request) {
		SortedMap<String, Object> params = prepareParams(request);
		generateSign(params, request.getPayKey());
		String requestXML = convert2Xml(params);
		
		try {
			String rspStr = HttpClientUtil.post(PayOrderQuery_URL, requestXML, HttpClientUtil.sslHttpClient(
					request.getKeyStorePath(), request.getKeyStorePassword(), request.getKeyStoreType()));
			if(rspStr.contains("xml")){
				String xmlRspStr = rspStr.replaceAll("\r|\n", "");
				WechatPayOrderQueryResult result= (WechatPayOrderQueryResult)JaxbUtil.converyToJavaBean(
						xmlRspStr, WechatPayOrderQueryResult.class);
				return result;
			 }
		} catch (IOException e) {
			logger.error("WeixinPayOrderQuery::execute failed url {}, params {}", PayOrderQuery_URL, requestXML);
		}
		
		return null;
	}
	
	private SortedMap<String, Object> prepareParams(WechatPayOrderQueryRequest request) {
		SortedMap<String, Object> params = new TreeMap<String, Object>();
		params.put("appid", request.getAppId());
		params.put("mch_id", request.getMchId());
		params.put("transaction_id", request.getTransactionId());
		params.put("out_trade_no", request.getOutTradeNo());
		params.put("nonce_str",generateNonceStr());
        
        return params;  
	}
}
